<!--
  拉卡拉SaaS： 【参数及费率的填写】 页面内容 活动报名

  @author yr
  @site https://www.jeequan.com
  @date 2023/11/29 10:35
-->
<template>
  <!-- 限制仅运营平台的【商户】和【服务商】可用 -->
  <div v-if="configMode == 'mgrMch' || configMode == 'mgrIsv'" style="background: #fff; margin-top: 20px">
    <div class="account-settings-info-view">
      <a-tabs v-model:activeKey="vdata.groupKey" tab-position="left" @change="selectTabs">
        <a-tab-pane v-if="configMode == 'mgrIsv'" key="activityInfo" tab="服务商活动">
          <page-header-wrapper>
            <a-card>
              <div style="padding-top: 20px; padding-left: 30px; padding-bottom: 10px">
                <a-button type="primary" :loading="vdata.btnLoadingActQuery" @click="queryActivity()">
                  重新拉取活动列表
                </a-button>
              </div>
              <a-table
                :data-source="vdata.activityList"
                :columns="actTableColumns"
                :pagination="false"
                :loading="vdata.btnLoadingActQuery"
                :row-key="'activityId'"
                :scroll="{ x: 'max-content' }"
                @resize-column=" (w, col) => {col.width = w} "
              >
                <template #bodyCell="{column,record}">
                  <template v-if="column.key === 'op'">
                    <!-- 操作列插槽 -->
                    <JeepayTableColumns>
                      <a-button type="link" @click="activityDetailFunc(record)">详情</a-button>
                      <a-button
                        v-if="allowJoinActivity(record.registrationStart, record.registrationEnd) && record.activityId" 
                        type="link"
                        :loading="vdata.btnLoadingJoin"
                        @click="isvJoinActivityFunc(record.activityId)"
                      >
                        报名
                      </a-button>
                    </JeepayTableColumns>
                  </template>
                </template>
              </a-table>
            </a-card>

            <!-- 活动详情页面组件  -->
            <ActivityDetailModal ref="activityInfoDetail" />
          </page-header-wrapper>
        </a-tab-pane>

        <!-- 服务商活动报名记录 商户在服务商已报名的记录中，挑选适合商户的活动 -->
        <a-tab-pane v-if="configMode == 'mgrMch'" key="mchQueryIsvJoinRecord" tab="合作商报名记录">
          <page-header-wrapper>
            <a-card>
              <div style="padding-top: 20px; padding-left: 30px; padding-bottom: 10px">
                <a-button type="primary" :loading="vdata.btnLoading" @click="queryJoinRecordFunc('QUERY_ISV_JOIN_RECORD')">
                  重新加载报名记录
                </a-button>
              </div>
              <a-table
                :data-source="vdata.joinRecord"
                :columns="isvJoinRecordTableColumns"
                :pagination="false"
                :loading="vdata.btnLoading"
                :row-key="'activityId'"
                :scroll="{ x: 'max-content' }"
                @resize-column=" (w, col) => {col.width = w} "
              >
                <template #bodyCell="{column,record}">
                  <template v-if="column.key === 'op'">
                    <!-- 操作列插槽 -->
                    <JeepayTableColumns>
                      {{ record.joinApplyDateStart }}
                      <a-button type="link" @click="queryJoinState(record, 'QUERY_ISV_JOIN_STATE')">获取最新状态</a-button>
                    </JeepayTableColumns>
                  </template>
                </template>
              </a-table>
            </a-card>
          </page-header-wrapper>
        </a-tab-pane>

        <!-- 商户活动报名 -->
        <a-tab-pane v-if="configMode == 'mgrMch'" key="mchJoinActivity" tab="商户活动报名">
          <a-form ref="mchActivityFormModel" :model="vdata.configData" layout="vertical" :rules="vdata.rules">
            <a-row justify="space-between" type="flex">
              <a-col :span="10">
                <a-form-item label="权益活动ID" name="activityId">
                  <a-input v-model:value.trim="vdata.configData.activityId" placeholder="请输入权益活动ID" />
                </a-form-item>
              </a-col>
            </a-row>
            
            <a-row justify="space-between" type="flex">
              <a-col :span="10">
                <a-form-item label="推荐人信息ID" name="refereeId">
                  <a-input v-model:value.trim="vdata.configData.refereeId" placeholder="请输入推荐人信息ID" />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row justify="space-between" type="flex">
              <a-col :span="10">
                <a-form-item label="分行编号" name="branchBankNo">
                  <a-input v-model:value.trim="vdata.configData.branchBankNo" placeholder="请输入分行编号" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-form-item class="bottom-btn" style="margin-top: 20px">
              <a-button type="primary" :loading="vdata.btnLoadingJoin" @click="mchJoinActivityFunc()"><check-circle-outlined />发起报名</a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane>
        
        <!-- 服务商活动报名记录 -->
        <a-tab-pane v-if="configMode == 'mgrIsv'" key="isvJoinRecord" tab="报名记录">
          <page-header-wrapper>
            <a-card>
              <div style="padding-top: 20px; padding-left: 30px; padding-bottom: 10px">
                <a-button type="primary" :loading="vdata.btnLoading" @click="queryJoinRecordFunc('QUERY_ISV_JOIN_RECORD')">
                  重新加载报名记录
                </a-button>
              </div>
              <a-table
                :data-source="vdata.joinRecord"
                :columns="isvJoinRecordTableColumns"
                :pagination="false"
                :loading="vdata.btnLoading"
                :row-key="'activityId'"
                :scroll="{ x: 'max-content' }"
                @resize-column=" (w, col) => {col.width = w} "
              >
                <template #bodyCell="{column,record}">
                  <template v-if="column.key === 'op'">
                    <!-- 操作列插槽 -->
                    <JeepayTableColumns>
                      <a-button type="link" @click="queryJoinState(record, 'QUERY_ISV_JOIN_STATE')">获取最新状态</a-button>
                      <a-button type="link" style="color: red" :loading="vdata.btnLoading" @click="delJoinRecordFunc(record.activityId, 'DEL_ISV_JOIN_RECORD')">删除</a-button>
                    </JeepayTableColumns>
                  </template>
                </template>
              </a-table>
            </a-card>
          </page-header-wrapper>
        </a-tab-pane>

        <!-- 商户活动报名记录 -->
        <a-tab-pane v-if="configMode == 'mgrMch'" key="mchJoinRecord" tab="报名记录">
          <page-header-wrapper>
            <a-card>
              <div style="padding-top: 20px; padding-left: 30px; padding-bottom: 10px">
                <a-button type="primary" :loading="vdata.btnLoading" @click="queryJoinRecordFunc('QUERY_MCH_JOIN_RECORD')">
                  重新加载报名记录
                </a-button>
              </div>
              <a-table
                :data-source="vdata.joinRecord"
                :columns="mchJoinRecordTableColumns"
                :pagination="false"
                :loading="vdata.btnLoading"
                :row-key="'activityId'"
                :scroll="{ x: 'max-content' }"
                @resize-column=" (w, col) => {col.width = w} "
              >
                <template #bodyCell="{column,record}">
                  <template v-if="column.key === 'op'">
                    <!-- 操作列插槽 -->
                    <JeepayTableColumns>
                      <a-button type="link" @click="queryJoinState(record, 'QUERY_MCH_JOIN_STATE')">获取最新状态</a-button>
                      <a-button type="link" style="color: red" :loading="vdata.btnLoading" @click="delJoinRecordFunc(record.activityId, 'DEL_MCH_JOIN_RECORD')">删除</a-button>
                    </JeepayTableColumns>
                  </template>
                </template>
              </a-table>
            </a-card>
          </page-header-wrapper>
        </a-tab-pane>
        <a-tab-pane v-if="configMode == 'mgrMch'" key="activityPeopleInfo" tab="推荐人信息">
          <page-header-wrapper>
            <a-card>
              <JeepaySearchForm :searchFunc="searchPeopleFunc" :resetFunc="()=>{ vdata.searchPeopleData = {} }">
                <jeepay-text-up v-model:value="vdata.searchPeopleData.nameOrJobNumber" :placeholder="'姓名或工号'" />
              </JeepaySearchForm>

              <!-- 列表渲染 -->
              <JeepayTable
                ref="infoTable"
                :init-data="true"
                :reqTableDataFunc="queryMchReferrerFunc"
                :tableColumns="actPeopleTableColumns"
                :searchData="vdata.searchPeopleData"
                rowKey="refereeId"
                @btnLoadClose="vdata.btnLoading=false"
              />
            </a-card>
          </page-header-wrapper>
        </a-tab-pane>
      </a-tabs>
    </div>
  </div>
  <div v-else>请联系运营平台</div>
</template>

<script lang="ts" setup>

import { ref, reactive, inject, getCurrentInstance, onMounted } from 'vue'
import { $joinActivity } from '@/api/manage'
import dayjs, { Dayjs } from 'dayjs'

const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties
const infoTable = ref()
const activityInfoDetail = ref()
const mchActivityFormModel = ref()

onMounted(()=>{
  initData() // 初始化数据
})

// 推荐人信息
const actPeopleTableColumns = reactive([
  { key: 'refereeId', fixed: 'left', title: '推荐人ID', dataIndex: 'refereeId' },
  { key: 'name', title: '推荐人姓名', dataIndex: 'name' },
  { key: 'jobNumber', title: '推荐人工号', dataIndex: 'jobNumber' },
  { key: 'bankName', title: '银行名称', dataIndex: 'bankName'},
  { key: 'branchBankName', title: '支行名称', dataIndex: 'branchBankName'},
  { key: 'branchBankNo', title: '分行编号', dataIndex: 'branchBankNo' }
])

// 活动信息
const actTableColumns = reactive([
  { key: 'activityId', fixed: 'left', title: '活动ID', dataIndex: 'activityId' },
  { key: 'activityName', title: '活动名称', dataIndex: 'activityName' },
  { key: 'comments', title: '备注', dataIndex: 'comments' },
  { key: 'effectiveStart', title: '有效期开始', dataIndex: 'effectiveStart'},
  { key: 'effectiveEnd', title: '有效期结束', dataIndex: 'effectiveEnd'},
  { key: 'registrationStart', title: '报名开始', dataIndex: 'registrationStart'},
  { key: 'registrationEnd', title: '报名结束', dataIndex: 'registrationEnd'},
  { key: 'op', title: '操作', fixed: 'right', align: 'center' }
])

// 服务商报名记录
const isvJoinRecordTableColumns = reactive([
  { key: 'activityId', fixed: 'left', title: '活动ID', dataIndex: 'activityId' },
  { key: 'agentNo', title: '服务商编号', dataIndex: 'agentNo' },
  { key: 'registerStatus', title: '报名状态代码', dataIndex: 'registerStatus' },
  { key: 'registerStatusDesc', title: '报名描述', dataIndex: 'registerStatusDesc' },
  { key: 'joinApplyDateStart', title: '报名发起时间', dataIndex: 'joinApplyDateStart' },
  { key: 'op', title: '操作', fixed: 'right', align: 'center' }
])

// 商户报名记录
const mchJoinRecordTableColumns = reactive([
  { key: 'activityId', fixed: 'left', title: '活动ID', dataIndex: 'activityId' },
  { key: 'externalCustomerNo', title: '商户编号', dataIndex: 'externalCustomerNo' },
  { key: 'registerStatus', title: '报名状态代码', dataIndex: 'registerStatus' },
  { key: 'registerStatusDesc', title: '报名描述', dataIndex: 'registerStatusDesc' },
  { key: 'joinApplyDateStart', title: '报名发起时间', dataIndex: 'joinApplyDateStart' },
  { key: 'op', title: '操作', fixed: 'right', align: 'center' }
])


// 接收父组件的参数注入： 配置方式 (判断是 运营平台  代理商 还是商户 )
let configMode : any = inject('configMode')
// 接收父组件的参数注入： mchAppId 或 isvNo (渠道配置的商户应用ID 或商户编号 )
let infoId : any = inject('appConfigModeByMchAppId')
// 接收父组件的参数注入： ifCode ( lklspay )
let ifCode : any = inject('appConfigModeBySelectedIfCode')

const vdata = reactive({
  btnLoading: false,
  btnLoadingActQuery: false, // 报名活动按钮loading
  btnLoadingJoin: false, // 报名按钮loading
  searchPeopleData: {} as any, // 推荐人查询对象
  configData: {} as any,
  activityList: [] as any, // 服务商活动列表
  joinRecord: [] as any, // 活动报名记录
  configDataDesen: {} as any, // 脱敏数据
  isvList: [],
  groupKey: '',
  rules: {
    activityId: [{ required: true, message: '请输入权益活动ID', trigger: 'blur' }]
  }
})

// 判断是否可参与报名
const allowJoinActivity = (registrationStart: Dayjs, registrationEnd: Dayjs) => {
  let allowJoin = false
  try {
    allowJoin = (dayjs() > dayjs(registrationStart)) && (dayjs() < dayjs(registrationEnd))
  } catch (error) {
    console.log('lklspay服务商活动查询-日期解析有误' + error)
    allowJoin = false
  }
  return allowJoin
}

// 请求table接口数据--推荐人信息（运营平台-商户应用）
function queryMchReferrerFunc(params){
  params.infoId = infoId
  params.configMode = configMode
  params.configType = 'QUERY_MCH_REFERRER'
  return $joinActivity(ifCode, params)
}

function searchPeopleFunc () { // 点击【查询】按钮点击事件 --推荐人信息（运营平台-商户应用）
  infoTable.value.refTable(true)
}

// 服务商活动查询接口
function queryActivity () { 
    vdata.btnLoadingActQuery = true // 打开按钮上的 loading
    const reqData:any = {}
    reqData.infoId = infoId
    reqData.configMode = configMode
    reqData.configType = 'QUERY_ISV_ACTIVITY'
    $joinActivity(ifCode, reqData).then( res => {
      vdata.activityList = res.records
      $infoBox.message.success('完成！')
      vdata.btnLoadingActQuery = false
    }).catch(res => {
      vdata.btnLoadingActQuery = false
    })
}

function activityDetailFunc (record: any) { // 活动详情
    activityInfoDetail.value.show(record)
}


// 服务商报名
function isvJoinActivityFunc (activityId) {
    $infoBox.confirmPrimary('确认报名吗？', '', () => {
      vdata.btnLoadingJoin = true // 打开按钮上的 loading
      const reqData:any = {}
      reqData.infoId = infoId
      reqData.configMode = configMode
      reqData.activityId = activityId
      reqData.configType = 'ISV_JOIN_ACTIVITY'
      $joinActivity(ifCode, reqData).then( res => {
        if (res.code != '000000') {
          $infoBox.message.error('发起失败，原因：' + res.message)
        } else {
          $infoBox.message.success('发起完成！')
        }
        
        vdata.btnLoadingJoin = false
      }).catch(error => {
        console.log('lklspay报名异常：' + error)
        vdata.btnLoadingJoin = false
      })
    })
}

// 商户报名
function mchJoinActivityFunc () {
  mchActivityFormModel.value.validate().then(valid =>{
    $infoBox.confirmPrimary('确认报名吗？', '', () => {
      vdata.btnLoadingJoin = true // 打开按钮上的 loading
      const reqData:any = {}
      reqData.infoId = infoId
      reqData.configMode = configMode
      reqData.activityId = vdata.configData.activityId
      reqData.configType = 'MCH_JOIN_ACTIVITY'
      $joinActivity(ifCode, reqData).then( res => {
        if (res.data.code != '000000') {
          $infoBox.message.error('发起失败，原因：' + res.data.message)
        } else {
          $infoBox.message.success('发起完成！')
        }
        
        vdata.btnLoadingJoin = false
      }).catch(res => {
        vdata.btnLoadingJoin = false
      })
    })
  })
}

// 查询 报名发起成功的记录（本地）
function queryJoinRecordFunc (configType) {
  vdata.btnLoading = true
  const reqData:any = {}
  reqData.infoId = infoId
  reqData.configMode = configMode
  reqData.configType = configType
  $joinActivity(ifCode, reqData).then( res => {
    vdata.joinRecord = res || []
    vdata.btnLoading = false
  }).catch(res => {
    vdata.btnLoading = false
  })
}

// 删除 报名发起成功的记录（本地）
function delJoinRecordFunc (activityId, configType) {
  vdata.btnLoading = true
  const queryType = configType == 'DEL_ISV_JOIN_RECORD' ? 'QUERY_ISV_JOIN_RECORD' : configType == 'DEL_MCH_JOIN_RECORD' ? 'QUERY_MCH_JOIN_RECORD' : ''
  const reqData:any = {}
  reqData.infoId = infoId
  reqData.configMode = configMode
  reqData.activityId = activityId
  reqData.configType = configType
  $joinActivity(ifCode, reqData).then( res => {
    queryJoinRecordFunc(queryType)
    vdata.btnLoading = false
  }).catch(res => {
    vdata.btnLoading = false
  })
}

// 查询服务商/商户报名状态
function queryJoinState (record, configType) {
  const reqData:any = {}
  reqData.infoId = infoId
  reqData.configMode = configMode
  reqData.activityId = record.activityId
  reqData.configType = configType
  reqData.joinApplyDateStart = record.joinApplyDateStart
  $joinActivity(ifCode, reqData).then( res => {
      if(res.data.errMsg){
        $infoBox.message.error(res.data.errMsg)
      } else {
        record.agentNo = res.data.agentNo || ''
        record.registerStatus = res.data.registerStatus || ''
        record.registerStatusDesc = res.data.registerStatusDesc || ''
        record.joinApplyDateStart = res.data.joinApplyDateStart || ''
        $infoBox.message.success('当前条目更新完成，活动ID：' + record.activityId)
      }
  }).catch(error => {
    console.log('lklspay查询服务商/商户报名状态异常：' + error)
  })
}

function selectTabs (key) { // 清空必填提示
  if (key) {
    vdata.groupKey = key
  }
  if (vdata.groupKey == 'isvJoinRecord') { // 查询服务商报名发起成功的记录（本地）
    queryJoinRecordFunc('QUERY_ISV_JOIN_RECORD')
  } else if (vdata.groupKey == 'mchJoinRecord') { // 查询商户报名发起成功的记录（本地）
    queryJoinRecordFunc('QUERY_MCH_JOIN_RECORD')
  } else if (vdata.groupKey == 'mchQueryIsvJoinRecord') { // 查询服务商报名发起成功的记录（本地） 商户查服务商
    queryJoinRecordFunc('QUERY_ISV_JOIN_RECORD')
  }
}

function initData () { // 需要初始化查询的操作
  if(!vdata.groupKey) {
      if(configMode == 'mgrIsv') {
        // 运营平台服务商角色
        vdata.groupKey = 'activityInfo' // 服务商活动查询（服务商的第一个tab）
        queryActivity()
      }else{
        vdata.groupKey = 'mchQueryIsvJoinRecord' // 商户活动报名（商户的第一个tab）
        queryJoinRecordFunc('QUERY_ISV_JOIN_RECORD')
      }
  }
}
</script>
